<template>
  <div>
    <el-card style="margin:15px;">
      <el-form :model="newsForm" ref="newsRef" :rules="newsRules">
        <!--新闻标题-->
        <el-form-item prop="newsTitle">
          <el-input placeholder="想一个优美的标题" style="width:600px;margin-left: 20px;" v-model="newsForm.newsTitle">
            <template slot="prepend">新闻标题:</template>
          </el-input>
        </el-form-item>

        <!--发布时间-->
        <el-form-item prop="newsTime" style="margin-left: 20px;">
          发布时间:
          <el-date-picker
              v-model="newsForm.newsTime"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <!--富文本编辑器-->
        <el-form-item prop="newsContent" style="margin: 20px;">
          <quill-editor ref="text"
                        style="height: 400px;margin-bottom: 50px;"
                        v-model="newsForm.newsContent"
                        class="myQuillEditor"
                        :options="editorOption"
          />
        </el-form-item>

        <!--新闻作者-->
        <el-form-item prop="newsTitle">
          <el-input placeholder="留下你的署名吧!" style="width:600px;margin-left: 20px;" v-model="newsForm.newsAuthor">
            <template slot="prepend">新闻作者:</template>
          </el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" style="margin:0 0 20px 20px" @click="addOrEditNews">提交</el-button>
    </el-card>
  </div>
</template>
<script>
import {quillEditor} from "vue-quill-editor";

export default {
  created() {
    /*获取编辑的新闻*/
    if (this.$route.params.newsId) {
      this.getNewsById(this.$route.params.newsId)
    }else{
      this.getNowTime()
    }
  },
  methods: {
    /*获取当前时间*/
    getNowTime() {
      const date = new Date();
      const year = date.getFullYear();
      const month = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
      const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
      const hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      const minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      const second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      this.newsForm.newsTime = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
    },
    /*提交新闻*/
    addOrEditNews() {
      //根据导航栏地址的id判断是添加还是跳转
      if(this.$route.params.newsId){
        /*编辑新闻*/
        this.$refs.newsRef.validate(async valid => {
          // 返回校验结果的布尔值
          if (!valid) return this.$message.error('请填写完整的新闻信息');
          //成功发送请求
          let result = await this.$http.news.reqEditNews(this.newsForm)
          console.log(result)
          if (result.code !== 200) return this.$message.error("新闻修改失败")
          this.$message.success("新闻修改成功")
          this.$router.push("/new/list")
        });
      }else{
        /*添加新闻*/
        //validate();接受一个回调函数拿到表单的验证结果
        this.$refs.newsRef.validate(async valid => {
          // 返回校验结果的布尔值
          // console.log(valid);
          if (!valid) return this.$message.error('请填写完整的新闻信息');
          //成功发送请求
          let result = await this.$http.news.reqAddNews(this.newsForm)
          if (result.code !== 200) return this.$message.error("新闻提交失败");
          this.$message.success("新闻提交成功")
          this.$router.push("/new/list")
        });
      }

    },
    /*根据id查询新闻*/
    async getNewsById(newsId) {
      let result = await this.$http.news.reqGetNewsById(newsId)
      if (result.code === 200) {
        this.newsForm = result.data.news
      }

    }
  },
  name: "AddNews",
  data() {
    return {
      newsForm: {
        newsContent: '',
        newsTime: '',
        newsTitle: ''
      },
      /*富文本功能设置*/
      editorOption: {
        modules: {
          toolbar: [
            [
              "bold",
              "italic",
              "underline",
              "strike",
              "link",
              "image",
              "code-block",
            ],
            [{'align': []}],    //对齐方式
            [{'header': [1, 2, 3, 4, 5, 6, false]}],     //几级标题
            [{'font': []}],     //字体
            [{'size': ['small', 'normal', 'large', 'huge']}],
            [{'color': []}, {'background': []}],     // 字体颜色，字体背景颜色
          ],
        },
      },
      /*表单校验对象*/
      newsRules: {
        newsContent: [{required: true, message: '文章内容不能为空', trigger: 'blur'}],
        newsTime: [{required: true, message: '发布时间不能为空', trigger: 'blur'}],
        newsTitle: [{required: true, message: '标题不能为空', trigger: 'blur'}],
        newsAuthor: [{required: true, message: '新闻作者不能为空', trigger: 'blur'}],
      },
      /*判断是否*/
    }
  },
  components: {quillEditor}

}
</script>
<style scoped>
</style>
